<template>
  <div class="">
    <a-modal
      v-model:visible="visible"
      :title="dialogTitle"
      :ok-loading="btnLoading"
      :modal-style="modalStyle"
      :body-style="bodyStyle"
      :mask-closable="false"
      @cancel="dialogCancel"
      @before-ok="dialogBeforeOk"
    >
      <a-form ref="formRef" :model="formModel">
        <a-form-item field="full_avatar" label="头像">
          <single-upload :single-file="singleFile" :show-file-list="false" accept="image/jpeg, image/png, image/gif" @uploadCallback="singleCallback"/>
        </a-form-item>
        <a-form-item
          field="username"
          label="账号"
          required
          :validate-trigger="['change', 'input']"
          :rules="[
            {
              required: true,
              message: '账号不能为空',
            },
          ]"
        >
          <a-input v-model="formModel.username" placeholder="请输入账号" style="width: 60%"/>
        </a-form-item>
        <a-form-item field="nickname" label="昵称">
          <a-input v-model="formModel.nickname" placeholder="请输入昵称" style="width: 60%"/>
        </a-form-item>
        <a-form-item v-if="formModel.id === ''" field="nickname" label="密码">
          <a-input-password v-model="formModel.password" placeholder="请输入密码" autocomplete="off" allow-clear style="width: 60%"/>
        </a-form-item>
        <a-form-item field="phone" label="手机">
          <a-input v-model="formModel.phone" placeholder="" style="width: 60%"/>
        </a-form-item>
        <a-form-item
          field="email"
          label="邮箱"
          :rules="[
            { validator: validateEmail },
          ]"
        >
          <a-input v-model="formModel.email" placeholder="" style="width: 60%"/>
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="formModel.remark" allow-clear :max-length="{ length: 120, errorOnly: true }" show-word-limit/>
        </a-form-item>
        <a-form-item field="sort" label="排序">
          <a-input-number v-model="formModel.sorting" :style="{width:'100px'}"/>
        </a-form-item>
        <a-form-item
          field="role_ids"
          label="角色"
          :rules="[
            {
              required: true,
              message: '至少选择一个角色',
            },
            {
              type: 'array',
              minLength: 1,
              message: '至少选择一个角色',
            },
          ]"
        >
<!--          <a-checkbox-group v-model="checkedRoleIds" @change="roleCheck">
            <a-checkbox :value="roles[index].id" v-for="(role, index) in roles" :key="index">{{ roles[index].name }}</a-checkbox>
          </a-checkbox-group>-->
          <a-select v-model="formModel.role_ids" multiple allow-search allow-clear>
            <a-option v-for="(role, index) in roles" :key="index" :value="role.id" :label="role.name" />
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="是否启用">
          <a-switch v-model="formModel.status" :checked-value="1" :unchecked-value="2"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
  import { ref } from 'vue';

  import useVisible from '@/hooks/visible';
  import { apiInfo, apiSave } from '@/api/admin';
  import { apiList as roleList } from '@/api/admin-role';
  import SingleUpload from '@/components/file-upload/index.vue';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    id: {
      type: [Number, String],
      default: '',
    },
    roles: {
      type: Array,
      default() {
        return [];
      },
    },
  });
  const emit = defineEmits(['saveCallback']);

  const baseFormModel = () => {
    return {
      id: '',
      created_at: '',
      updated_at: '',
      avatar: '',
      full_avatar: '',
      username: '',
      nickname: '',
      password: '',
      phone: '',
      email: '',
      remark: '',
      role_ids: [],
      sorting: 100,
      status: 1,
    };
  };
  const formRef = ref();
  const formModel = ref(baseFormModel());
  const modalStyle = {
    width: '40%',
    height: '65%',
    maxWidth: '650px',
  };
  const bodyStyle = {
    height: 'calc(100% - 108px)',
    overflow: 'auto',
  };

  const { visible, setVisible } = useVisible(false);
  const dialogTitle = ref();
  const btnLoading = ref(false);

  const checkStrictly = ref(false);
  const checkedRoleIds = ref([]); // 选中的角色
  const roles = ref([]); // 角色
  const singleFile = ref({
    url: '',
    path: '',
    field: 'avatar',
  });

  // 邮箱 格式校验
  function validateEmail(value, callback) {
    if (/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(value)) {
      callback(); // 校验通过
    } else {
      callback('邮箱格式不正确');
    }
  }

  // 表单重置
  const reset = async () => {
    formModel.value = baseFormModel();
    await formRef.value?.resetFields();
    checkedRoleIds.value = [];
    singleFile.value.url = '';
    singleFile.value.path = '';
  };
  const fetchData = async (row = {}) => {
    await getRoles();

    setVisible(true);
    dialogTitle.value = '新增';
    if (row.id) {
      dialogTitle.value = `编辑ID: ${row.id}`;
    }
    await reset();
    if (row.id) {
      const { data } = await apiInfo({ id: row.id });
      formModel.value = data;
      checkedRoleIds.value = data.role_ids;
      singleFile.value.url = formModel.value.full_avatar;
      singleFile.value.path = formModel.value.avatar;
    }
  };
  // 提交
  const submit = async (done) => {
    try {
      const ruleRes = await formRef.value?.validate();
      if (!ruleRes) {
        await apiSave(formModel.value);
        done();
        emit('saveCallback');
      } else {
        done(false);
      }
    } catch (err) {
      done(false);
    } finally {
      done(false);
    }
  };
  const getRoles = async () => {
    const { data } = await roleList();
    roles.value = data.data;
  };
  // 角色选择
  const roleCheck = (checkedKeys) => {
    formModel.value.role_ids = checkedKeys;
  };

  // 文件上传回调
  const singleCallback = (file) => {
    singleFile.value.url = file.url;
    singleFile.value.path = file.filepath;
    formModel.value.avatar = file.filepath;
  };

  const dialogCancel = () => {
    setVisible(false);
    reset();
  };
  const dialogBeforeOk = (done) => {
    submit(done);
    // done();
    // done(false);
  };

  // 暴露方法【给父级调用】
  defineExpose({
    fetchData,
  });
</script>

<style scoped lang="less">

</style>
